package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.ErpCollectProductTask;
import com.erp.gather.domain.bo.ErpCollectProductTaskBo;
import com.erp.gather.domain.vo.ErpCollectProductTaskVo;
import com.erp.gather.mapper.ErpCollectProductTaskMapper;
import com.erp.gather.service.IErpCollectProductTaskService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 采集商品任务Service业务层处理
 *
 * @author erp
 * @date 2023-03-13
 */
@RequiredArgsConstructor
@Service
public class ErpCollectProductTaskServiceImpl implements IErpCollectProductTaskService {

	private final ErpCollectProductTaskMapper baseMapper;

	/**
	 * 查询采集商品任务
	 */
	@Override
	public ErpCollectProductTaskVo queryById(Long id) {
		return baseMapper.selectVoById(id);
	}

	/**
	 * 查询采集商品任务列表
	 */
	@Override
	public TableDataInfo<ErpCollectProductTaskVo> queryPageList(ErpCollectProductTaskBo bo, PageQuery pageQuery) {
		LambdaQueryWrapper<ErpCollectProductTask> lqw = buildQueryWrapper(bo);
		Page<ErpCollectProductTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
		return TableDataInfo.build(result);
	}

	/**
	 * 查询采集商品任务列表
	 */
	@Override
	public List<ErpCollectProductTaskVo> queryList(ErpCollectProductTaskBo bo) {
		LambdaQueryWrapper<ErpCollectProductTask> lqw = buildQueryWrapper(bo);
		return baseMapper.selectVoList(lqw);
	}

	private LambdaQueryWrapper<ErpCollectProductTask> buildQueryWrapper(ErpCollectProductTaskBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<ErpCollectProductTask> lqw = Wrappers.lambdaQuery();
		lqw.eq(StringUtils.isNotBlank(bo.getCollectUrl()), ErpCollectProductTask::getCollectUrl, bo.getCollectUrl());
		lqw.eq(StringUtils.isNotBlank(bo.getCategory()), ErpCollectProductTask::getCategory, bo.getCategory());
		lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ErpCollectProductTask::getStatus, bo.getStatus());
		lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpCollectProductTask::getRevision, bo.getRevision());
		lqw.eq(bo.getCollectUserId() != null, ErpCollectProductTask::getCollectUserId, bo.getCollectUserId());
		lqw.isNotNull(Objects.equals(bo.getHasCollectUserId(), "1"), ErpCollectProductTask::getCollectUserId);
		lqw.isNull(Objects.equals(bo.getHasCollectUserId(), "0"), ErpCollectProductTask::getCollectUserId);

		lqw.orderByDesc(ErpCollectProductTask::getUpdateTime);

		return lqw;
	}

	/**
	 * 新增采集商品任务
	 */
	@Override
	public Map<String, Object> insertByBo(ErpCollectProductTaskBo bo) {
		// ErpCollectProductTask add = BeanUtil.toBean(bo, ErpCollectProductTask.class);
		// validEntityBeforeSave(add);
		// boolean flag = baseMapper.insert(add) > 0;
		// if (flag) {
		// bo.setId(add.getId());
		// }
		
		// 根据角色判断是否是运营
		String roles = SecurityUtils.getRoles();
		
		Map<String, Object> map = new HashMap<>();
		List<String> alreadyUrls = new ArrayList<>();
		List<String> errorCategoryUrls = new ArrayList<>();
		Integer count = 0;
		String[] urls = bo.getCollectUrl().replace("\n", ",").split(",");
		for (String url : urls) {
			try {
				if (Strings.isBlank(url)) {
					continue;
				}
//                if (url.contains("https://www.pangbosupply.com/") || url.contains("http://www.pangbosupply.com/") || url.contains("http://pangbosupply.com/")) {
//                    url = url.contains("&goods_id=") ? url.substring(0, url.indexOf("&goods_id=")) : url;
//                } else {
//                    url = url.substring(0, url.indexOf(".html") + 5);
//                }
				if (baseMapper.selectCount(Wrappers.lambdaQuery(new ErpCollectProductTask())
						.like(ErpCollectProductTask::getCollectUrl, url)) > 0) {
					alreadyUrls.add(url);
					continue;
				}
				if (Objects.equals(bo.getCategory(), "1")) {
//					if (!url.contains(".aliexpress.") && !url.contains("api.aliseeks.com")) {
//						errorCategoryUrls.add(url);
//						continue;
//					}
				}
				if (Objects.equals(bo.getCategory(), "2")) {
					if (!url.contains("detail.1688.com/")) {
						errorCategoryUrls.add(url);
						continue;
					}
				}
				if (Objects.equals(bo.getCategory(), "3")) {
					if (!url.contains("b2csupply.com/")) {
						errorCategoryUrls.add(url);
						continue;
					}
					if (roles.contains("erp-operate")) { // 运营
						bo.setClassifyLabel("1719179918137212929");
					}
				}
				if (roles.contains("erp-operate")) { // 运营
					bo.setCollectType(2);
				} else if (roles.contains("erp-user")) { // erp
					bo.setCollectType(3);
				} else {
					bo.setCollectType(1);
				}

				ErpCollectProductTask add = BeanUtil.toBean(bo, ErpCollectProductTask.class);
				add.setCollectUrl(url);
				baseMapper.insert(add);
				count++;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		map.put("count", count);
		map.put("urls", alreadyUrls);
		map.put("errorCategoryUrls", errorCategoryUrls);

		return map;
	}

	/**
	 * 修改采集商品任务
	 */
	@Override
	public Boolean updateByBo(ErpCollectProductTaskBo bo) {
		ErpCollectProductTask update = BeanUtil.toBean(bo, ErpCollectProductTask.class);
		validEntityBeforeSave(update);
		return baseMapper.updateById(update) > 0;
	}

	/**
	 * 保存前的数据校验
	 */
	private void validEntityBeforeSave(ErpCollectProductTask entity) {
		// TODO 做一些数据校验,如唯一约束
	}

	/**
	 * 批量删除采集商品任务
	 */
	@Override
	public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		if (isValid) {
			// TODO 做一些业务上的校验,判断是否需要校验
		}
		return baseMapper.deleteBatchIds(ids) > 0;
	}
}
